package service.proxy;

import entity.User;
import exception.DuplicateUsernameException;
import exception.UserDisabledException;
import exception.UserNotFoundException;
import framework.bean.factory.ObjectFactory;
import framework.bean.factory.annotation.Component;
import framework.service.exception.ServiceException;
import framework.service.transaction.TransactionManager;
import service.UserService;

@Component("userService")
public class UserServiceProxy implements UserService {

    private UserService userService;

    public UserServiceProxy() {
        userService= (UserService) ObjectFactory.getObject("userServiceTarget");
    }

    @Override
    public void regist(User user) throws DuplicateUsernameException {
        TransactionManager transactionManager= (TransactionManager) ObjectFactory.getObject("transaction");

        try {

            transactionManager.begin();

            userService.regist(user);

            transactionManager.commit();

        } catch (DuplicateUsernameException e) {
            transactionManager.rollback();
            throw e;
        } catch (Exception e) {
            transactionManager.rollback();
            throw new ServiceException(e);
        }
    }

    @Override
    public User login(String username, String password) throws UserNotFoundException, UserDisabledException {
        TransactionManager transactionManager= (TransactionManager) ObjectFactory.getObject("transaction");

        User user=null;

        try {

            transactionManager.begin();

            user= userService.login(username,password);

            transactionManager.commit();

        } catch (UserNotFoundException e) {
            transactionManager.rollback();
            throw e;
        } catch (UserDisabledException e) {
            transactionManager.rollback();
            throw e;
        } catch (Exception e) {
            transactionManager.rollback();
            throw new ServiceException(e);
        }

        return user;
    }

    @Override
    public void validateUsername(String username) throws DuplicateUsernameException {
        TransactionManager transactionManager= (TransactionManager) ObjectFactory.getObject("transaction");

        try {
            transactionManager.begin();

            userService.validateUsername(username);

            transactionManager.commit();
        } catch (DuplicateUsernameException e) {
            transactionManager.rollback();
            throw e;
        } catch (Exception e) {
            transactionManager.rollback();
            throw new ServiceException(e);
        }
    }
}
